<script setup>
import { appBinding, appSelectedTypeTree, appTypeTree } from '@/api/system/app'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['update:visible', 'sure'])
const dataSource = ref([{}])
const filterText = ref('')
const treeRef = ref()
const bindingLoading = ref(false)
const pageLoading = ref(false)
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}
const handleSave = () => {
  bindingLoading.value = true
  appBinding(props.id, treeRef.value.getCheckedKeys()).then(res => {
    ElMessage.success('保存成功')
    bindingLoading.value = false
    emit('update:visible', false)
  })
}
const reset = () => {
  emit('update:visible', false)
}
watch(
  () => props.visible,
  async (newValue, oldValue) => {
    if (newValue) {
      pageLoading.value = true
      appTypeTree().then(res => {
        dataSource.value = res.data
        appSelectedTypeTree(props.id).then((res) => {
          treeRef.value.setCheckedKeys(res.data.map(item => item.appTypeId))
        }).finally(() => {
          pageLoading.value = false
        })
      })
    } else {
      treeRef.value.setCheckedKeys([])
    }
  },
)
watch(filterText, (val) => {
  treeRef.value.filter(val)
})
</script>

<template>
  <el-dialog :close-on-click-modal="false" align-center v-model="visible" title="应用权限" @close="reset" width="60%">
    <el-form v-loading="editLoading" label-width="80px">
    <el-form-item label="应用权限">
      <el-input v-model="filterText" :prefix-icon="Search" placeholder="搜索" clearable />
    </el-form-item>
    <el-tree v-loading='pageLoading' ref='treeRef' show-checkbox default-expand-all :data="dataSource" :filter-node-method="filterNode" node-key='appTypeId' :props="{label: 'name'}" @check-change="handleSelectionChange" />
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="bindingLoading">确认</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>

</style>
